package com.showgood.util {
	import com.showgood.config.Config;
	import com.showgood.util.cache.SimpleLRUCache;
	import com.showgood.util.NetResLoader;
	import flash.display.Bitmap;
	import spark.primitives.BitmapImage;
	/**
	 * 资源管理器
	 * @author bianpeng
	 */
	public class AssetsUtil {
		import org.as3commons.logging.getLogger;
		import org.as3commons.logging.ILogger;
		private var _logger:ILogger = getLogger(this);
		
		// 图片cache
		private var _imageCache:SimpleLRUCache = new SimpleLRUCache(100);
		/**
		 * 从cache中获得图片
		 * @param	imageUrl
		 */
		public function updateImage(image:BitmapImage, imageUrl:String):void {
			var _bitmap:Bitmap = _imageCache.itemFor(imageUrl) as Bitmap;
			if (!!_bitmap) {
				image.source = _bitmap;
			}
			else {
				// 排队从URL请求
				var _loader:NetResLoader = new NetResLoader(imageUrl, imageUrl);
				_loader.addEventListener(NetResLoaderEvent.COMPLETE, function(event:NetResLoaderEvent):void {
					image.source = event._content;
					_imageCache.put(imageUrl, event._content);
				} );
				_loader.load();
			}
		}
		// man info cache
		private var _manInfoCache:SimpleLRUCache = new SimpleLRUCache(5);
		public function get manInfoCache():SimpleLRUCache { return _manInfoCache; }
		
		public function AssetsUtil() {
			
		}
		// 这里把需要载入的东西放到这里来
		public function prepareLoaders(loaders:Vector.<NetResLoader>):void {
			loaders.push(makeSwfLoader('simple', 'items.swf', ['Cube', 'Army', 'ViewArea', 'city_001', 'city_002']));
			loaders.push(makeSwfLoader('config', 'config.swf', null));
			//loaders.push(makeSwfLoader('world', 'city_001.png', null));
			//loaders.push(makeSwfLoader('world', 'city_002.png', null));
		}
		
		public function finsihLoad(loaders:Vector.<NetResLoader>):void {
			_logger.info('all preload finished! ');
		}
		
		private function makeSwfUrl(dir:String, swf:String):String {
			return 'resource/' + dir +'/' + swf + '?v=' + Config.VERSION;
		}
		
		private function makeSwfLoader(dir:String, swf:String, symbols:Array):NetResLoader {
			return new NetResLoader(swf, makeSwfUrl(dir,swf), symbols);
		}
		
		////////////////////////////////////////////////////////////////////
		//
		// 条件编译一下
		//
		////////////////////////////////////////////////////////////////////
		public static function getAvatar(img:String):String {
			return Config.RESOURCE_BASE + '/avatar/' + img + '.jpg';
		}
		
		private static var _instance:AssetsUtil;
		public static function get instance():AssetsUtil {
			if (!_instance) {
				_instance = new AssetsUtil();
			}
			return _instance;
		}
	}

}

